package tables

import (
	"encoding/json"
	"peilian-api/app/global/variable"
)

const (
	QNo     = "no_question"
	QNormal = "normal_question"
	QExtra  = "extra_question"
	QHunter = "hunter_question"
	QCommon = "common_question"
)

// 要点映射
var ConstMainPointNum = map[string]int{
	"one_point":   1,
	"two_point":   2,
	"three_point": 3,
	"four_point":  4,
}

type QuestionResp struct {
	*Question
	SkillTagIds []*Criteria `json:"skill_tag" gorm:"-"`
}

type Question struct {
	Model
	CareerID    uint   `json:"career_id,omitempty" gorm:"comment:职业id"`
	Career      Career `json:"-" gorm:"-"`
	ParentText  string `json:"parent_text,omitempty" gorm:"comment:父问题内容"`
	Text        string `json:"text" gorm:"type:longtext;comment:问题内容"`
	PointType   uint   `json:"point_type,omitempty" gorm:"type:tinyint(3);default:0;comment:缺少要点内容,需要的追问 1,2,3,4"`
	IsOrder     uint   `json:"is_order,omitempty" gorm:"type:tinyint(3);default:0;comment:全部缺少要点，默认取 1,2,3,4"`
	PointText   string `json:"-" gorm:"comment:要点覆盖词 [{\"type\":\"one_point\",\"label\":\"要点一:表明观点or立场/概括提炼问题\",\"value\":[\"当下\",\"如今\",\"现象\"]}]"`
	AnsAnalysis string `json:"ans_analysis" gorm:"comment:答案解析参考"`
	Type        string `json:"type,omitempty" gorm:"type:varchar(20);comment:问题类型:normal_question |  extra_question | hunter_question |common_question |star_st |star_a |star_r"`
	Tag         string `json:"tag,omitempty" gorm:"type:varchar(20);comment:hunter_quesion对应的标签"`
	Criteria    string `json:"criteria,omitempty" gorm:"type:varchar(20);comment:考察能力"`
	KeyWords    string `json:"key_words,omitempty" gorm:"comment:题目解析涉及到的标签词"` // 新版web报告用到该字段
	//KeyWords     string `json:"key_words" gorm:"comment:主题关键词[\"贷款\",\"创业\"]"`
	Level        string `json:"level" gorm:"type:varchar(20);not null;default:基础;comment:题目分级[\"基础\",\"进阶\"]"`
	Video        string `json:"video" gorm:"type:varchar(255);not null;comment:视频url"`
	VideoStatus  int    `gorm:"default:0;comment:视频生成状态,0-未生成，1-已完成，2-生成失败 3-生成中" json:"video_status"`
	SpecialVideo string `json:"special_video,omitempty" gorm:"type:varchar(255);not null;comment:专项练习视频url"`
	PcVideo      string `json:"pc_video" gorm:"type:varchar(255);not null;comment:pc端视频url"`

	QuestionOrigin string `json:"question_origin,omitempty" gorm:"type:varchar(512);comment:题目来源"`
	AnsAnalysisTag string `json:"ans_analysis_tag,omitempty" gorm:"type:varchar(512);comment:解析tag"`

	User_id uint `json:"user_id" gorm:"default:0;comment:创建者id"`
	//Skill_tag string `json:"skill_tag" gorm:"type:longtext;type:varchar(512);comment:技能标签"`
	SkillTagIds []uint      `json:"skill_tag" gorm:"-"`
	SkillTags   []*Criteria `json:"-" gorm:"many2many:criteria_relation"`

	CriteriaTag  string     `json:"criteria_tag"` // 专项练习，算法评分使用,不入库
	Source       int        `json:"source" gorm:"type:tinyint(1);default:1;comment:1|2,1为系统内置，2为用户自定义"`
	Bid          int        `json:"bid" gorm:"default:0;comment:业务的数据id"`
	ProfessionId *uint      `json:"profession_id" gorm:"index;comment:岗位所在的专业信息"`
	Profession   Profession `json:"profession"`
}

func (q *Question) SetCustomKeyWords() error {
	if q.SkillTagIds == nil {
		return nil
	}
	skills := make([]*Criteria, 0)
	if err := variable.DB.MySQL.Select("ID", "CriteriaName").Where("id in (?)", q.SkillTagIds).
		Find(&skills).Error; err != nil {
		return err
	}
	skillIdNameMap := make(map[uint]string)
	for _, qs := range skills {
		skillIdNameMap[qs.ID] = qs.CriteriaName
	}
	names := make([]string, 0)
	for _, id := range q.SkillTagIds {
		n, exists := skillIdNameMap[id]
		if exists {
			names = append(names, n)
		}
	}
	keyWords, _ := json.Marshal(names)
	q.KeyWords = string(keyWords)
	return nil
}

//func (q *Question) MarshalJSON() ([]byte, error) {
//	type Alias Question
//	aux := struct {
//		*Alias
//		CreateAt string `json:"created_at"`
//		UpdateAt string `json:"updated_at"`
//	}{
//		Alias:    (*Alias)(q),
//		CreateAt: q.CreatedAt.Format("2006-01-02 15:04:05"),
//		UpdateAt: q.UpdatedAt.Format("2006-01-02 15:04:05"),
//	}
//
//	return json.Marshal(&aux)
//}

// 定义要点解析的数据结构
type PointTextStruct struct {
	Type  string   `json:"type"`
	Label string   `json:"label"`
	Value []string `json:"value"`
}

// 查询字段
type DResult struct {
	CareerId uint   `json:"career_id"`
	Criteria string `json:"criteria"`
}

func (q *Question) TableName() string {
	return "question"
}

// 根据条件查询题目
func (q *Question) GetQuestionsByWhereMap(whereMap map[string]interface{}) ([]Question, error) {
	var questions []Question
	if d := variable.DB.MySQL.Model(&q).Where(whereMap).Find(&questions); d.Error != nil {
		return questions, d.Error
	}
	return questions, nil
}

// 根据条件查询题目
func (q *Question) GetQuestionsByWhereStr(whereStr string) ([]Question, error) {
	var questions []Question
	if d := variable.DB.MySQL.Model(&q).Where(whereStr).Find(&questions); d.Error != nil {
		return questions, d.Error
	}
	return questions, nil
}

func (q *Question) UpdateQuestionsById(updates map[string]interface{}, id int) error {
	if d := variable.DB.MySQL.Model(q).Where("id = ?", id).Updates(updates).Limit(1); d.Error != nil {
		return d.Error
	}
	return nil
}

func (q *Question) GetQuestionsByWhere(whereMap map[string]interface{}, whereStr string) ([]Question, interface{}) {
	var questions []Question
	if len(whereMap) == 0 {
		if d := variable.DB.MySQL.Model(Question{}).Where(whereStr).Find(&questions); d.Error != nil {
			return questions, d.Error
		}
	} else if len(whereStr) == 0 {
		if d := variable.DB.MySQL.Model(Question{}).Where(whereMap).Find(&questions); d.Error != nil {
			return questions, d.Error
		}
	} else {
		if d := variable.DB.MySQL.Model(Question{}).Where(whereMap).Where(whereStr).Find(&questions); d.Error != nil {
			return questions, d.Error
		}
	}

	return questions, nil
}
